import { useState } from 'react';
import { useIntl, getLocale } from 'umi';
import { useHistory } from 'dva';
import { Toast } from 'antd-mobile';

import { getShareImage } from '../../servers/service';

import styles from './index.less';

import IconHome from '../../assets/icon/home@2x.png';
import IconShare from '../../assets/icon/share@2x.png';

const ButtonItem = ({ icon, label, onClick }) => {
  return (
    <div className={styles.button} onClick={onClick}>
      <img src={icon} className={styles.buttonIcon} />
      <div className={styles.buttonLabel}>{label}</div>
    </div>
  );
};

const FloatButton = ({ params, url }) => {
  const history = useHistory();
  const intl = useIntl();
  const lang = () => getLocale()?.split('-')[0]?.toUpperCase();

  const [shareVisible, setShareVisible] = useState(false);
  const [shareUrl, setShareUrl] = useState();

  const toHome = () => {
    history.push('/');
  };

  const onShare = async () => {
    if (shareUrl) {
      setShareVisible(true);
      document.body.style.overflow = 'hidden';
      return;
    }
    try {
      document.body.style.overflow = 'hidden';
      Toast.loading('海报生成中', 0, () => {}, true);
      const res = await getShareImage(url, params);
      setShareVisible(true);
      setShareUrl(res.url);
      Toast.hide();
    } catch (error) {
      Toast.hide();
    }
  };

  return (
    <>
      {shareVisible && (
        <div
          className={styles.shareBox}
          onClick={() => {
            setShareVisible(false);
            document.body.style.overflow = 'auto';
          }}
        >
          <img src={shareUrl} className={styles.shareImage} />
        </div>
      )}
      <div className={styles.floatButton}>
        <ButtonItem icon={IconHome} label={intl.formatMessage({ id: 'HOME' })} onClick={toHome} />
        <ButtonItem
          icon={IconShare}
          label={intl.formatMessage({ id: 'SHARE' })}
          onClick={onShare}
        />
      </div>
    </>
  );
};

export default FloatButton;
